//
//  SeletPhotoAlbum.swift
//  Swift_xhl
//
//  Created by xhl_dabaoMac on 2021/5/13.
//

import Foundation
import MobileCoreServices
import UIKit
import TZImagePickerController

public extension UIViewController {

    
    /// 选择图片
    /// - Parameters:
    ///   - selectedAssets: 已经选择的图片，用来标识已经选中
    ///   - maxImageCount: 最大支持的选择图片数量，默认是9
    ///   - columnNumber: 每行显示几张图片，默认4
    ///   - allowPickingVideo: 是否允许选择视频。默认不允许
    ///   - allowPickingImage: 是否允许选择图片。默认允许
    ///   - isSelectOriginalPhoto: 是否允许选择原图 默认允许
    ///   - didFinishPickingPhotosHandle: 选择图片后的回调
    
    /**
     ex：
     
     self.cq.pushToPhotoAlbum(assetsOld) {

         photos, assets, isSelectOriginalPhoto in
         
            // do something
         
     }
     */
    
    func pushToPhotoAlbum(_ selectedAssets:Array<Any>,
                          _ maxImageCount:Int = 9,
                          _ columnNumber:Int = 4,
                          _ allowPickingVideo:Bool = false,
                          _ allowPickingImage:Bool = true,
                          _ isSelectOriginalPhoto:Bool = true,
                          _ didFinishPickingPhotosHandle:@escaping ([UIImage]?,[Any]?,Bool) -> () )
    
    
    {
        let imagePicker = TZImagePickerController(maxImagesCount: maxImageCount,
                                                  columnNumber: columnNumber,
                                                  delegate:nil)
        
        imagePicker?.isSelectOriginalPhoto = isSelectOriginalPhoto
        imagePicker?.allowPickingVideo = allowPickingVideo
        imagePicker?.allowPickingImage = allowPickingImage
        imagePicker?.selectedAssets = NSMutableArray(array: selectedAssets)
//        imagePicker?.didFinishPickingPhotosHandle = {
//            (photos:[UIImage]?,assets:[Any]?,isSelectOriginalPhoto:Bool) in
//            didFinishPickingPhotosHandle(photos,assets,isSelectOriginalPhoto)
//        }
        imagePicker?.didFinishPickingPhotosHandle = didFinishPickingPhotosHandle
        imagePicker?.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(imagePicker!, animated: true, completion: nil)
        
    }
    

    func pushToVideoAlbum(_ columnNumber:Int = 4,
                          _ didFinishPickingVideoHandle:@escaping (UIImage?,PHAsset?) -> () )
    
    {
        let imagePicker = TZImagePickerController(maxImagesCount: 1,
                                                  columnNumber: columnNumber,
                                                  delegate:nil)
        imagePicker?.allowPickingVideo = true
        imagePicker?.allowPickingImage = false
        //void (^didFinishPickingVideoHandle)(UIImage *coverImage,PHAsset *asset);
        imagePicker?.didFinishPickingVideoHandle = didFinishPickingVideoHandle
        imagePicker?.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(imagePicker!, animated: true, completion: nil)
        
    }
    
    func chooseVideo() {
        let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertVC.addAction(UIAlertAction(title: "打开相机", style: .default, handler: { a in
            if !UIImagePickerController.isCameraDeviceAvailable(UIImagePickerController.CameraDevice.rear) {
                self.showAlert()
                return
            }
            
            let vc = TakeVideoViewController { url, image in
                print("");
            }
            self.present(vc, animated: true, completion: nil)
        }));
        
        alertVC.addAction(UIAlertAction(title: "从相册选择", style: .default, handler: { a in
            self.pushToVideoAlbum { image, phasset in
                
            }
        }));
        
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil));
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
//    - (void)choosePhotoWithNeedCrop:(BOOL)isNeedCrop
//                    cropAspectRatio:(CGSize)cropAspectRatio
//                       isCircleCrop:(BOOL)isCircleCrop
//                           callback:(void(^)(UIImage *image))callback
//
    func choosePhoto(isNeedCrop: Bool, cropAspectRatio: CGSize, isCircleCrop: Bool, callBack:@escaping(_ photo: UIImage?)->Void) {
        let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alertVC.addAction(UIAlertAction(title: "打开相机", style: .default, handler: { a in
            if !UIImagePickerController.isCameraDeviceAvailable(UIImagePickerController.CameraDevice.rear) {
                self.showAlert()
                return
            }
            
            let imageVC = XhlImagePickerController()
            imageVC.sourceType = .camera
            imageVC.isAllowTakeVideo = false
            imageVC.isAllowTakePicture = true
            imageVC.isAllowEditPicture = isNeedCrop
            imageVC.isNeedCircleCrop = isCircleCrop
            imageVC.cropAspectRatio = cropAspectRatio
            
            imageVC.doneBlock = { image, url in
                callBack(image);
                imageVC.dismiss(animated: true, completion: nil)
            }
            self.present(imageVC, animated: true, completion: nil)
        }));
        
        alertVC.addAction(UIAlertAction(title: "从相册选择", style: .default, handler: { a in
            let imageVc = TZImagePickerController()
            imageVc.maxImagesCount = 1;
            imageVc.showSelectBtn = false;
            imageVc.allowTakePicture = true;
            imageVc.allowTakeVideo = false;
            imageVc.allowPickingVideo = false;
            imageVc.allowCrop = isNeedCrop;
            imageVc.needCircleCrop = isCircleCrop;
            imageVc.maxImagesCount = 1;
            imageVc.didFinishPickingPhotosHandle = {photos, assets, isSelectOriginalPhoto in
                callBack(photos?.first);
            }
            imageVc.modalPresentationStyle = .fullScreen
            self.present(imageVc, animated: true, completion: nil)
        }));
        
        alertVC.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil));
        
        self.present(alertVC, animated: true, completion: nil)
    }
    
    fileprivate func showAlert() {
        
        let alertVC = UIAlertController(title: "提示", message: "您的设备不支持打开相机", preferredStyle: .alert);
        alertVC.addAction(UIAlertAction(title: "确认", style: .cancel, handler: nil));
        self.present(alertVC, animated: true, completion: nil)
    }
}

class XhlImagePickerController: UIImagePickerController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
//    @property (nonatomic, copy) void (^doneBlock)(UIImage *_Nullable image, NSURL *_Nullable videoUrl);
    /// 是否允许拍照
    var isAllowTakePicture: Bool = false
    /// 是否允许编辑图片
    var isAllowEditPicture: Bool = false
    /// 是否需要圆形剪裁
    var isNeedCircleCrop: Bool = false
    /// 图片剪裁比例
    var cropAspectRatio: CGSize?
    /// 是否允许录制视频
    var isAllowTakeVideo: Bool = false
    
    var doneBlock: ((_ image: UIImage?, _ videoUrl: NSURL?) -> Void)?
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let type = info[UIImagePickerController.InfoKey.mediaType] as! String
        if type == "public.image" {
            let photo = info[UIImagePickerController.InfoKey.originalImage];
                if (photo != nil && self.doneBlock != nil) {
//                    if (self.isAllowEditPicture) {
//                        self.editPhoto(photo: photo as! UIImage) { image in
//                            self.doneBlock!(image, nil);
//                        }
//                    } else {
                        self.doneBlock!(photo as! UIImage, nil);
//                    }
                }
            } else if (type == "public.movie") {
                let videoUrl = info[UIImagePickerController.InfoKey.mediaURL]
                if (videoUrl != nil && self.doneBlock != nil) {
                    self.doneBlock!(nil, videoUrl as! NSURL);
                }
            }
    }
    
    
    func updateMeidaTypes() {
        var mediaTypes:Array<String> = Array()
        if (self.isAllowTakePicture) {
            mediaTypes.append(kUTTypeImage as String)
        }
        if (self.isAllowTakeVideo) {
            mediaTypes.append(kUTTypeMovie as String)
        }
        self.mediaTypes = mediaTypes;
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.updateMeidaTypes()
    }
    
//    func editPhoto(photo: UIImage, callBack:@escaping(_ photo: UIImage?)->Void) {
//        let style = self.isNeedCircleCrop ? TOCropViewCroppingStyle.circular : TOCropViewCroppingStyle.default;
//        let cropViewController = TOCropViewController(croppingStyle: style, image: photo)
//        if (style == TOCropViewCroppingStyle.default &&  !__CGSizeEqualToSize(CGSize.zero, self.cropAspectRatio ?? CGSize.zero)) {
//            cropViewController.aspectRatioLockEnabled = true;
//            cropViewController.resetAspectRatioEnabled = false;
//            cropViewController.customAspectRatio = self.cropAspectRatio!;
//            self.addChild(cropViewController)
//            cropViewController.view.frame = self.view.bounds
//            cropViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//            self.view.addSubview(cropViewController.view)
//            cropViewController.onDidCropToRect = { photo, rect, angle in
//                self.view.removeFromSuperview()
//                self.removeFromParent()
//                callBack(photo)
//            };
//
//            cropViewController.onDidFinishCancelled = { isFinished in
//                callBack(nil)
//                self.view.removeFromSuperview()
//                self.removeFromParent()
//                self.dismiss(animated: true, completion: nil)
//            }
//        }
//    }
    
}
